const Router = require("@koa/router");
const router = new Router();
const startConnect = require("../db");
const { verifyToken } = require("../core/util");

//获取指定阅览室信息
router.get("/reading_room_one", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("获取指定阅览室信息", isValid);
  if (isValid) {
    if (isValid.scope === 1) {
      const { id } = ctx.request.query;
      console.log("id", ctx);
      const sql = `select id,name,located,open_time,open,seats,total from reading_rooms where id='${id}'`;
      await startConnect(sql).then((room) => {
        if (room) {
          ctx.body = {
            tag: true,
            room,
          };
        } else {
          ctx.body = 404;
        }
      });
    } else if (isValid.scope === 0) {
      const { id } = ctx.request.query;
      console.log("id", ctx);
      const sql = `select * from reading_rooms where id='${id}'`;
      await startConnect(sql).then((room) => {
        room.open = room.open == 1 ? true : false;
        if (room) {
          ctx.body = {
            tag: true,
            room,
          };
        } else {
          ctx.body = 404;
        }
      });
    } else {
      ctx.body = 404;
    }
  } else {
    ctx.body = 404;
  }
});

//获取所有阅览室信息
router.get("/reading_room", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("获取所有阅览室信息", isValid);
  if (isValid) {
    if (isValid.scope === 1) {
      const sql = `select id,name,located,open_time,open,seats,total from reading_rooms`;

      await startConnect(sql).then((rooms) => {
        rooms.forEach((v, index) => {
          console.log(v.open == 1 ? "true" : "false");
          rooms[index].open = v.open == 1 ? true : false;
        });
        console.log("data", rooms);
        ctx.body = {
          tag: true,
          rooms,
        };
      });
    } else if (isValid.scope === 0) {
      const sql = `select * from reading_rooms`;
      await startConnect(sql).then((rooms) => {
        ctx.body = {
          tag: true,
          rooms,
        };
      });
    } else {
      ctx.body = 404;
    }
  } else {
    ctx.body = 404;
  }
});

module.exports = router;
